<?php
/**
 * 后台基类
 * 
 + ----------------------------------------------------- 
 * Date 2013-3-8
 + -----------------------------------------------------
 */
class CommonAction extends Action {

    public function _initialize() {
    	//排除不用验证的模块
		if(!isset($_SESSION[C('USER_AUTH_KEY')]) && C('NOT_AUTH_MODULE')!=MODULE_NAME) {
			$this->redirect(C('USER_AUTH_GATEWAY'));
		}
		//echo GROUP_NAME;exit;
		// 当前栏目
		if($_GET['mid']){
			$menu_model = M('Menu');
			$current_menu=$menu_model->table(C('DB_PREFIX').'menu as m')
									->join('left join '.C('DB_PREFIX').'menu_type as t on(m.type_id=t.id)')
									->field('m.*,t.model')
									->where('m.id='.$_GET['mid'])
									->find();
			$this->assign('current_menu', $current_menu);
		}
		//配置
		$this->_config();
    }
    
    /**
     * 所有配置参数
     */
    private function _config(){
    	$config = M("Config");
    	$list = $config->getField('name,value');
    	if(!empty($list)&&is_array($list)){
    		foreach($list as $k=>$v){
    			C(strtoupper($k),$v);
    		}
    	}
    }
	
    /**
     * 新增标签，在添加文章的时候
     * @param string $tags 多个用空格分开
     * @param int $id 记录ID
     * @param string $module 当前模块名
     */
    public function saveTag($tags, $id, $model = MODULE_NAME) {
    	if (!empty($tags) && !empty($id)) {
    		$Tag = M("Tag");
    		$Tagged = M("Tagged");
    		// 记录已经存在的标签
    		$exists_tags = $Tagged->where("model='{$model}' and record_id={$id}")->getField("id,tag_id");
    		$Tagged->where("model='{$model}' and record_id={$id}")->delete();
    		$tags = explode(' ', $tags);
    		foreach ($tags as $key => $val) {
    			$val = trim($val);
    			if (!empty($val)) {
    				$tag = $Tag->where("model='{$model}' and name='{$val}'")->find();
    				if ($tag) {
    					// 标签已经存在
    					if (!in_array($tag['id'], $exists_tags)) {
    						$Tag->where('id=' . $tag['id'])->setInc('count');
    					}
    				} else {
    					// 不存在则添加
    					$tag = array();
    					$tag['name'] = $val;
    					$tag['count'] = 1;
    					$tag['color']	=	getRandColor(); //随机颜色
    					$tag['model'] = $model;
    					$tag['add_time'] = time();
    					if($result = $Tag->add($tag)){
    						// 写入日志
    					}
    					$tag['id'] = $result;
    				}
    				// 记录tag关联信息
    				$t = array();
    				$t['user_id'] = Session::get(C('USER_AUTH_KEY'));
    				$t['model'] = $model;
    				$t['record_id'] = $id;
    				$t['add_time'] = time();
    				$t['tag_id'] = $tag['id'];
    				if($Tagged->add($t)){
    					// 写入日志
    				}
    			}
    		}
    	}
    }
    
    /**
     * 默认列表首页
     */
    public function index() {
        //列表过滤器，生成查询Map对象
        $map = $this->_search();
        if (method_exists($this, '_filter')) { //字段过滤  在模型类中定义
            $this->_filter($map);
        }
        $model = D($this->getActionName());
        if (!empty($model)) {
            $this->_list($model, $map);
        }
        $this->display();
        return;
    }
	
    /**
      +----------------------------------------------------------
     * 根据表单生成查询条件
     * 进行列表过滤
      +----------------------------------------------------------
     * @access protected
      +----------------------------------------------------------
     * @param string $name 数据对象名称
      +----------------------------------------------------------
     * @return HashMap
      +----------------------------------------------------------
     * @throws ThinkExecption
      +----------------------------------------------------------
     */
    protected function _search($name = '') { 
        //生成查询条件
        if (empty($name)) {
            $name = $this->getActionName();
        }
        $model = M($name);
        $map = array();
        foreach ($model->getDbFields() as $key => $val) {
            if (substr($key, 0, 1) == '_')
                continue;
            if (isset($_REQUEST[$val]) && $_REQUEST[$val] != '') {
				$like_fields=C('LIKE_MATCH_FIELDS');
				if(!empty($like_fields)){
					$like_fields=@explode('|',C('LIKE_MATCH_FIELDS'));
					if(in_array($val,$like_fields)){
						$map[$val]=array('like','%'.$_REQUEST[$val].'%');
					}
				}else{
               		$map[$val] = $_REQUEST[$val];
				}
            }
        }
        return $map;
    }
    
	/**
	 * 自定义的条件过滤
	 * @param string $fields
	 * @param string $name
	 * @return Ambigous <unknown, multitype:, string>
	 */
	protected function _mysearch($fields,$name = '') {
		$keyword=isset($_REQUEST['keyword']) ? trim($_REQUEST['keyword']) : '';
        //生成查询条件
        if (empty($name)) {
            $name = $this->getActionName();
        }
        $model = M($name);
        $map = $where = $real_fields = array();
		$all_fields=$model->getDbFields();
		if(is_array($fields)){
			foreach($fields as $key=>$field){ //过滤字段
				if(in_array($field,$all_fields)){
					if (substr($field, 0, 1) == '_')   //为了防止_complex,_string_,_logic等系统关键词
						continue;
					$real_fields[]=$field;
				}
			}
			if(count($real_fields) > 0){
				foreach($real_fields as $key=>$field){
					if (isset($keyword) && !empty($keyword)) {
						$where[$field] = array('like','%'.$keyword.'%');
					}
				}
				if(count($real_fields) > 1 && $keyword){
					$where['_logic']='or';
					$map['_complex']=$where;
				}else{
					$map=$where;
				}
			}
		}
        return $map;
    }
	

    /**
      +----------------------------------------------------------
     * 根据表单生成查询条件
     * 进行列表过滤
      +----------------------------------------------------------
     * @access protected
      +----------------------------------------------------------
     * @param Model $model 数据对象
     * @param HashMap $map 过滤条件
     * @param string $sortBy 排序
     * @param boolean $asc 是否正序
      +----------------------------------------------------------
     * @return void
      +----------------------------------------------------------
     * @throws ThinkExecption
      +----------------------------------------------------------
     */
    protected function _list($model, $map = array(), $sortBy = '', $asc = false) {
		$all_fields=$model->getDbFields();
        //排序字段 默认为主键名
        if (isset($_REQUEST['order'])) {
            $order = $_REQUEST['order'];
        } else {
            $order = !empty($sortBy) ? $sortBy : $model->getPk();
        }
        // 排序方式
        if (isset($_REQUEST['sort'])) {
            $sort = $_REQUEST['sort']=='asc' ? 'asc' : 'desc';
        } else {
            $sort = $asc ? 'asc' : 'desc';
        }
        // 按自定义排序
		if(in_array('sort_order',$all_fields)){
			$order = 'sort_order';
			$sort = 'asc';
		}
        //取得满足条件的记录数
        $count = $model->where($map)->count('id');
        import("ORG.Util.Page");
        //创建分页对象 listRows 每页显示数量
        if (!empty($_REQUEST['listRows'])) {
            $listRows = $_REQUEST['listRows'];
        } else {
            $listRows = '15';
        }
        $p = new Page($count, $listRows);
        //分页查询数据
        $list = $model->where($map)->order($order . ' ' . $sort)->limit($p->firstRow . ',' . $p->listRows)->select();
		
        //分页显示
        $page = $p->show();
        //列表排序显示
        $sort = $sort == 'desc' ? 1 : 0;                     //排序方式
        
        //模板赋值显示
        $this->assign('listRows',$listRows);
        $this->assign('pagesize',$this->_getPageSize());
        $this->assign('list', $list);
        $this->assign('sort', $sort);
        $this->assign('order', $order);
        $this->assign("page", $page);
		$this->assign("map", $map);
        Cookie::set('_currentUrl_', __SELF__);
        return;
    }
    
	/**
	 * 默认读取
	 */
	public function add() {
		$this->display();
	}
	
	/**
	 * 默认新增数据
	 */
    public function insert() {
        $model = D($this->getActionName());
        if (false === $model->create()) {
            $this->error($model->getError());
        }
        // 若有上传文件
        if(!empty($_FILES['image']['name'])){
        	// 图片上传 自定义目录
        	$info=$this->_upload($this->getSavePath($_FILES['image']['name']),true,C('SITE_THUMB_WIDTH'),C('SITE_THUMB_HEIGHT'),true);
        	// 图片存入
        	$model->image = $image = isset($info[0]['savename']) ? $info[0]['savepath'].$info[0]['savename']: '';
        }else{
        	// $this->error('请上传图片');
        }
        if ($result = $model->add()) {
        	//保存附件信息
			$Attach=M("Attach");
			$data=array(
					'record_id'	=> 	$result,
					'path'		=> 	$image,
					'model' 	=> 	MODULE_NAME,
					'size'		=> 	getFileSize($image),
					'add_time'	=>	time()
			);
			if(isset($image)){
				$Attach->data($data)->add();
			}
            $this->success(L('添加成功'),$this->getReturnUrl());
        } else {
            $this->error(L('添加失败'));
        }
    }
	
    /**
     * 默认编辑
     */
    public function edit() {
        $model = M($this->getActionName());
        $id = $_REQUEST[$model->getPk()];
        $data = $model->find($id);
        $this->assign('data', $data);
        $this->display('add');
    }
    
	/**
	 * 默认编辑保存编辑数据
	 */
    public function update() {
        $model = D($this->getActionName());
        $data=$model->getById($_POST[$model->getPk()]);
        if (false === $model->create()) {
            $this->error($model->getError());
        }
        //若有上传信息
        if(!empty($_FILES['image']['name'])){
        	$info=$this->_upload($this->getSavePath($_FILES['image']['name']),true,C('SITE_THUMB_WIDTH'),C('SITE_THUMB_HEIGHT'),true);
        	if(isset($info[0]['savename'])){
        		//成功后删除原来图片
        		@unlink($data['image']);
        		$model->image = $image = $info[0]['savepath'].$info[0]['savename'];
        	}else{
        		$model->image = $image=	$data['image'];
        	}
        }else{
        	$model->image = $image = $data['image'];
        }
        if (false !== $model->save()) {
			//更新附件信息
			$Attach=M("Attach");
			$tach['record_id']=intval($_POST[$model->getPk()]);
			$tach['path']=$image;
			$tach['model']=MODULE_NAME;
			$tach['size']=getFileSize($image);
			$tach['add_time']=time();
			if(isset($image) && $image != $data['image']){
				//删除原附件
				if($this->_delAttach($_POST[$model->getPk()])){
					//插入新附件
					$Attach->data($tach)->add();
				}
			}
            $this->success(L('编辑成功'),$this->getReturnUrl());
        } else {
            $this->error(L('编辑失败'));
        }
    }
	
    /**
     * 默认删除操作
     */
    public function delete() {
    	//删除指定记录
    	$model = M($this->getActionName());
    	if (!empty($model)) {
    		$pk = $model->getPk();
    		$id = $_REQUEST[$pk];
    		if (isset($id)) {
    			$condition = array($pk => array('in', explode(',', $id)));
    			if (false !== $model->where($condition)->delete()) {
    				$this->success('删除成功！',$this->getReturnUrl());
    			}else{
    				$this->success('删除失败！');
    			}
    		}else{
    			$this->error('非法操作！');
    		}
    	}
    }
    
    /**
     * Ajax编辑
     */
	public function ajax_edit(){
		$valid='error';
		$model=M($this->getActionName());
		$field=trim($_REQUEST['field']);
		$pk = $model->getPk();
		$id=intval($_REQUEST[$pk]);
		$val=$_REQUEST['val'];
		$data=array(
			$field =>$val
		);
		$map[$pk]=$id;
		if($model->where($map)->save($data)){
			$valid='ok';
		}
		die($valid);
	}
	
	/**
	 * Ajax启用
	 */
	public function ajax_change(){
		$valid='error';
		$model=M($this->getActionName());
		$pk=$model->getPk();
		$id=intval($_REQUEST[$pk]);
		$map=array(
			$pk=>$id
		);
		$field=trim($_REQUEST['field']);
		$info=$model->where($map)->field($field)->find();
		$data=array(
			$field=>($info[$field]==1) ? 0 : 1,
		);
		$save=$model->where($map)->save($data);
		if($save){
			$valid='ok';
		}
		die($valid);
	}
	
	/**
	 * Ajax删除
	 */
	public function ajax_delete() {
        //删除指定记录
        $model = M($this->getActionName());
        if (!empty($model)) {
            $pk = $model->getPk();
            $id = $_REQUEST[$pk];
            if (isset($id)) {
                $condition = array($pk => array('in', explode(',', $id)));
                if (false !== $model->where($condition)->delete()) {
                    $this->ajaxReturn(1,'删除成功！',1);
                }else{
					 $this->ajaxReturn(0,'删除失败！',0);
				}
            }else{
				 $this->ajaxReturn(0,'非法操作！',0);
			}
        }
    }
    /**
      +----------------------------------------------------------
     * 默认列表选择操作用于select控件
     *
      +----------------------------------------------------------
     * @access public
      +----------------------------------------------------------
     * @return string
      +----------------------------------------------------------
     * @throws FcsException
      +----------------------------------------------------------
     */
    protected function select($fields = 'id,name', $title = '') {
        $map = $this->_search();
        //创建数据对象
        $Model = M($this->getActionName());
        //查找满足条件的列表数据
        $list = $Model->where($map)->getField($fields);
        $this->assign('selectName', $title);
        $this->assign('list', $list);
        $this->display();
        return;
    }
	
    /**
     +----------------------------------------------------------
     * 验证码显示 用的是TP的验证码库
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @return void
     +----------------------------------------------------------
     * @throws FcsException
     +----------------------------------------------------------
     */
    function verify() {
    	import("ORG.Util.Image");
    	Image::buildImageVerify();
    }
    
    /**
     * 分页数据长度
     * @return multitype:string
     */
    protected function _getPageSize(){
    	return array(
    			'10'=>'每页10条',
    			'15'=>'每页15条',
    			'30'=>'每页30条'
    	);
    }

    /**
      +----------------------------------------------------------
     * 取得操作成功后要返回的URL地址
     * 默认返回当前模块的默认操作
     * 可以在action控制器中重载
      +----------------------------------------------------------
     * @access public
      +----------------------------------------------------------
     * @return string
      +----------------------------------------------------------
     * @throws ThinkExecption
      +----------------------------------------------------------
     */
    function getReturnUrl() {
		$param='';
		if($_GET['mid']){
			$param.='&mid='.$_GET['mid'];
		}
		if($_GET['p']){
			$param.='&p='.$_GET['p'];
		}
        return __URL__ . '?' . C('VAR_MODULE') . '=' . MODULE_NAME . '&' . C('VAR_ACTION') . '=' . C('DEFAULT_ACTION').$param;
    }
    
    /**
     * 获取附件存储路径
     */
    public function getSavePath($name,$level=3,$model=MODULE_NAME){
    	$name	=	md5($name);
    	// 使用子目录
    	$dir   ='';
    	for($i=0; $i<$level; $i++) {
    		$dir	.=	$name{$i}.'/';
    	}
    	$dir = UPLOAD_PATH.'/'.$model.'/'.$dir;
    	return $dir;
    }
    
    /**
     +----------------------------------------------------------
     * 默认上传操作
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @return void
     +----------------------------------------------------------
     * @throws ThinkExecption
     +----------------------------------------------------------
     */
    public function upload($save_path='', $is_thumb=true, $thumb_with=150, $thumb_height=150, $del_origin=false) {
    	//如果有文件上传
    	if (!empty($_FILES)) {
    		// 上传附件并保存信息到数据库
    		$this->_upload($save_path, $is_thumb, $thumb_with, $thumb_height, $del_origin);
    	}
    }
	
    /**
     +----------------------------------------------------------
     * 上传方法
     +----------------------------------------------------------
     * @param string $save_path 保存的路径，模板中会做路径替换
     * @param bool $is_thumb 是否要生成缩略图
     * @param int $thumb_with 缩略图做大宽度
     * @param int $thumb_height 缩略图最大高度
     * @param bool $del_origin 是否删除原图 ，当$is_thumb为真时有效
     +----------------------------------------------------------
     * 上传方法
     +----------------------------------------------------------
     */
    protected function _upload($save_path='', $is_thumb=true, $thumb_with=150, $thumb_height=150, $del_origin=false){
    	import("ORG.Net.UploadFile");
    	//导入上传类
    	$upload = new UploadFile();
    	//设置上传文件大小 3M
    	$upload->maxSize = 3*1024*1024;
    	//设置上传文件类型
    	$upload->allowExts = explode(',', 'jpg,gif,png,jpeg');
    	//设置附件上传目录
    	if(!is_dir($save_path)){
    		createDir($save_path);
    	}
    	$upload->savePath = !is_dir($save_path) ? UPLOAD_PATH : $save_path;
    	//设置需要生成缩略图，仅对图像文件有效 bool
    	$upload->thumb = $is_thumb;
    	// 设置引用图片类库包路径
    	$upload->imageClassPath = 'ORG.Util.Image';
    	//设置需要生成缩略图的文件后缀
    	$upload->thumbPrefix = 'thumb_';
    	//生产2张缩略图 //设置缩略图最大宽度
    	$upload->thumbMaxWidth = $thumb_with ? $thumb_with : 150;
    	//设置缩略图最大高度
    	$upload->thumbMaxHeight = $thumb_height ? $thumb_height : 150;
    	//设置上传文件规则
    	$upload->saveRule = 'uniqid';
    	//删除原图 bool
    	$upload->thumbRemoveOrigin = $is_thumb ? $del_origin : false;
    	if (!$upload->upload()) {
    		//捕获上传异常
    		$this->error($upload->getErrorMsg());
    	} else {
    		//取得成功上传的文件信息
    		$uploadList = $upload->getUploadFileInfo();
    		if($is_thumb){
    			$uploadList[0]['savename']=$upload->thumbPrefix.$uploadList[0]['savename'];
    		}
    		return $uploadList;
    		//import("@.ORG.Image");
    		//给m_缩略图添加水印, Image::water('原文件名','水印图片地址')
    		//Image::water($uploadList[0]['savepath'] . 'm_' . $uploadList[0]['savename'], APP_PATH.'Tpl/Public/Images/logo.png');
    		//$_POST['image'] = $uploadList[0]['savename'];
    	}
    
    }
    
    /**
     * 删除附件操作
     * @param int $id
     * @param string $model
     * @return boolean
     */
    protected function _delAttach($id,$model=MODULE_NAME){
    	$valid=false;
    	if($id){
    		$attach_map=array(
    				'record_id'=>$id,
    				'model'		=>$model,
    		);
    		$model=M("Attach");
    		$images=$model->where($attach_map)->select();
    		if(count($images)>0){
    			foreach ($images as $k=>$v){
    				if(file_exists($v['path'])){
    					@unlink($v['path']);
    				}
    			}
    		}
    		$model->where($attach_map)->delete();
    		$valid=true;
    	}
    	return $valid;
    }
    
	 /**
     * 手动缓存数据文件
     * @param string $name
     * @param string $fields
     */
    public function cache($name = '', $fields = '') {
        $name = $name ? $name : $this->getActionName();
        $Model = M($name);
        $list = $Model->select();
        $data = array();
        foreach ($list as $key => $val) {
            if (empty($fields)) {
                $data[$val[$Model->getPk()]] = $val;
            } else {
                // 获取需要的字段
                if (is_string($fields)) {
                    $fields = explode(',', $fields);
                }
                if (count($fields) == 1) {
                    $data[$val[$Model->getPk()]] = $val[$fields[0]];
                } else {
                    foreach ($fields as $field) {
                        $data[$val[$Model->getPk()]][] = $val[$field];
                    }
                }
            }
        }
        $savefile = $this->getCacheFilename($name);
        // 所有参数统一为大写
        $content = "<?php\nreturn " . var_export(array_change_key_case($data, CASE_UPPER), true) . ";\n?>";
        if (file_put_contents($savefile, $content)) {
            $this->success('缓存生成成功！');
        } else {
            $this->error('缓存失败！');
        }
    }
	
    /**
     * 获取缓存的数据
     * @param string $name
     * @return string
     */
    protected function getCacheFilename($name = '') {
        $name = $name ? $name : $this->getActionName();
        return DATA_PATH . '~' . strtolower($name) . '.php';
    }

    /**
      +----------------------------------------------------------
     * 文件上传功能，支持多文件上传、保存数据库、自动缩略图
      +----------------------------------------------------------
     * @access protected
      +----------------------------------------------------------
     * @param string $module 附件保存的模块名称
     * @param integer $id 附件保存的模块记录号
      +----------------------------------------------------------
     * @return void
      +----------------------------------------------------------
     * @throws ThinkExecption
      +----------------------------------------------------------
     */
    protected function _uploadMore($module = '', $recordId = '') {
        import("ORG.Net.UploadFile");
        $upload = new UploadFile();
        // 自定义上传规则
        $upload = $this->_upload_init($upload);
        // 记录上传成功ID
        $uploadId = array();
        $savename = array();
        //执行上传操作
        if (!$upload->upload()) {
            if ($this->isAjax() && isset($_POST['_uploadFileResult'])) {
                $uploadSuccess = false;
                $ajaxMsg = $upload->getErrorMsg();
            } else {
                //捕获上传异常
                $this->error($upload->getErrorMsg());
            }
        } else {
            //取得成功上传的文件信息
            $uploadList = $upload->getUploadFileInfo();
            $remark = $_POST['remark'];
            //保存附件信息到数据库
            if ($uploadRecord) {
                $Attach = M('Attach');
                //启动事务
                $Attach->startTrans();
            }
            if (!empty($_POST['_uploadFileTable'])) {
                //设置附件关联数据表
                $module = $_POST['_uploadFileTable'];
            }
            if (!empty($_POST['_uploadRecordId'])) {
                //设置附件关联记录ID
                $recordId = $_POST['_uploadRecordId'];
            }
            if (!empty($_POST['_uploadFileId'])) {
                //设置附件记录ID
                $id = $_POST['_uploadFileId'];
            }
            if (!empty($_POST['_uploadFileVerify'])) {
                //设置附件验证码
                $verify = $_POST['_uploadFileVerify'];
            }
            if (!empty($_POST['_uploadUserId'])) {
                //设置附件上传用户ID
                $userId = $_POST['_uploadUserId'];
            } else {
                $userId = isset($_SESSION[C('USER_AUTH_KEY')]) ? $_SESSION[C('USER_AUTH_KEY')] : 0;
            }
            foreach ($uploadList as $key => $file) {
                $savename[] = $file['savepath'] . $file['savename'];
                $sourcename[] = $file['name'];
                if ($uploadRecord) {
                    // 附件数据需要保存到数据库
                    //记录模块信息
                    unset($file['key']);
                    $file['module'] = $module;
                    $file['record_id'] = $recordId ? $recordId : 0;
                    $file['user_id'] = $userId;
                    $file['verify'] = $verify ? $verify : '0';
                    $file['remark'] = $remark[$key] ? $remark[$key] : ($remark ? $remark : '');
                    $file['status'] = 1;
                    $file['create_time'] = time();
                    if (empty($file['hash'])) {
                        unset($file['hash']);
                    }
                    //保存附件信息到数据库
                    if ($upload->uploadReplace) {
                        if (!empty($id)) {
                            $vo = $Attach->getById($id);
                        } else {
                            $vo = $Attach->where("module='" . $module . "' and record_id=" . $recordId)->find();
                        }
                        if ($vo) {
                            // 如果附件为覆盖方式 且已经存在记录，则进行替换
                            $id = $vo[$Attach->getPk()];
                            if ($uploadFileVersion) {
                                // 记录版本号
                                $file['version'] = $vo['version'] + 1;
                                // 备份旧版本文件
                                $oldfile = $vo['savepath'] . $vo['savename'];
                                if (is_file($oldfile)) {
                                    if (!is_dir(dirname($oldfile) . '/_version/')) {
                                        mkdir(dirname($oldfile) . '/_version/');
                                    }
                                    $bakfile = dirname($oldfile) . '/_version/' . $id . '_' . $vo['version'] . '_' . $vo['savename'];
                                    $result = rename($oldfile, $bakfile);
                                }
                            }
                            // 覆盖模式
                            $Attach->where("id=" . $id)->save($file);
                            $uploadId[] = $id;
                        } else {
                            $uploadId[] = $Attach->add($file);
                        }
                    } else {
                        //保存附件信息到数据库
                        $uploadId[] = $Attach->add($file);
                    }
                }
            }
            if ($uploadRecord) {
                //提交事务
                $Attach->commit();
            }
            $uploadSuccess = true;
            $ajaxMsg = '';
        }

        // 判断是否有Ajax方式上传附件
        // 并且设置了结果显示Html元素
        if ($this->isAjax() && isset($_POST['_uploadFileResult'])) {
            // Ajax方式上传参数信息
            $info = Array();
            $info['success'] = $uploadSuccess;
            $info['message'] = $ajaxMsg;
            //设置Ajax上传返回元素Id
            $info['uploadResult'] = $_POST['_uploadFileResult'];
            if (isset($_POST['_uploadFormId'])) {
                //设置Ajax上传表单Id
                $info['uploadFormId'] = $_POST['_uploadFormId'];
            }
            if (isset($_POST['_uploadResponse'])) {
                //设置Ajax上传响应方法名称
                $info['uploadResponse'] = $_POST['_uploadResponse'];
            }
            if (!empty($uploadId)) {
                $info['uploadId'] = implode(',', $uploadId);
            }
            $info['savename'] = implode(',', $savename);
            $info['name'] = implode(',', $sourcename);
            $this->ajaxUploadResult($info);
        }
        return;
    }

    /**
      +----------------------------------------------------------
     * 下载附件
      +----------------------------------------------------------
     * @access public
      +----------------------------------------------------------
     * @return void
      +----------------------------------------------------------
     * @throws FcsException
      +----------------------------------------------------------
     */
    public function download() {
        $id = $_GET['id'];
        $Attach = M("Attach");
        if ($Attach->getById($id)) {
            $filename = $Attach->savepath . $Attach->savename;
            if (is_file($filename)) {
                $showname = auto_charset($Attach->name, 'utf-8', 'gbk');
                $Attach->where('id=' . $id)->setInc('download_count');
                import("ORG.Net.Http");
                Http::download($filename, $showname);
            }
        }
    }

    public function saveSort() {
        $seqNoList = $_POST['seqNoList'];
        if (!empty($seqNoList)) {
            //更新数据对象
            $model = M($this->getActionName());
            $col = explode(',', $seqNoList);
            //启动事务
            $model->startTrans();
            foreach ($col as $val) {
                $val = explode(':', $val);
                $model->id = $val[0];
                $model->sort = $val[1];
                $result = $model->save();
                if (false === $result) {
                    break;
                }
            }
            //提交事务
            $model->commit();
            if ($result) {
                //采用普通方式跳转刷新页面
                $this->success('更新成功');
            } else {
                $this->error($model->getError());
            }
        }
    }

    protected function getAttach($module = '') {
        $module = empty($module) ? $this->getActionName() : $module;
        //读取附件信息
        $id = $_REQUEST['id'];
        $Attach = M('Attach');
        $attachs = $Attach->where("module='" . $module . "' and record_id=$id")->select();
        //模板变量赋值
        $this->assign("attachs", $attachs);
    }

}

?>